import serial
import sys

COM_PORT_NUM = 2
DEBUG = False

def log(message):
    sys.stdout.write(message + '\n')
    sys.stdout.flush()

def logDebug(message):  if DEBUG: log('DBG: ' + message)
def logInfo(message):   log('INF: ' + message)
def logError(message):  log('ERR: ' + message)

class AccumulatedEvent:
    def __init__(self):
        self.clear()

    def clear(self):
        self.state = 0 #0 - nothing received, 1 - one 0x91 received, 2 - 0x92 received
        self.cidobject  = ''
        self.cidcode    = ''
        self.cidrazdel  = ''
        self.cidchannel = ''
        self.cidnumber  = ''

    def accumulate(self, buff):
        if str(buff[0]) != str(0x8F):
            logError('accumulate: buff[0] is not 0x8F: ' + str(buff[0]))
            return
        while True:
            if self.state == 0 and str(buff[1]) == str(0x91):
                self.cidobject  = str(buff[2]) + str(buff[3])
                self.cidcode    = str(buff[3])
                self.state = 1
                logDebug('accumulate: successfull 0x91(0)')
                return
            if self.state == 1 and str(buff[1]) == str(0x92):
                self.cidcode = self.cidcode + str((buff[2] & 0xF0) >> 4)
                self.cidrazdel = str((buff[2] & 0x0F)) + str((buff[3] & 0xF0) >> 4)
                self.cidchannel = str((buff[3] & 0x0F)) + str(buff[4])
                self.state = 2
                logDebug('accumulate: successfull 0x92(1)')
                return
            if self.state == 2 and str(buff[1]) == str(0x90):
                self.cidnumber = str(buff[2]) + str(buff[3]) + str(buff[4])
                logInfo('event received: %s,%s,%s,%s,%s' % (self.cidobject, self.cidcode, self.cidrazdel, self.cidchannel, self.cidnumber))
                self.clear()
                return
            if str(buff[1]) == str(0x91):
                self.clear()
                continue
            logError('accumulate: unexpected buffer[%s]: %s' % (str(buff[1]),str(buff)))
            return
            break

def main():
    p = serial.Serial(port=COM_PORT_NUM, baudrate=1200, bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, timeout=0)
    e = AccumulatedEvent()
    logInfo('port is opened')

    while True:
        try:

            d = p.readline()
            if d == '': continue
            e.accumulate(d)

        except Exception, err:
            logError('main: ' + str(err))
            continue

    p.close()
    logInfo('port is closed')

if __name__ == '__main__': main()
